package com.github.common.utils.spring;

import java.io.UnsupportedEncodingException;
import java.util.List;

import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

/**
 * <p>User: Mu Yunlong
 * <p>Date: 2016年2月26日 下午10:23:50
 * <p>Version: 1.0
 */
public final class SpringBindingResultWrapper
{
    private SpringBindingResultWrapper()
    {
      throw new Error("工具类不能实例化");
    }

    public static String warpErrors(BindingResult errors)
    {
      if (errors.hasErrors()) {
        String errorMsg = "";

        List fieldErrors = errors.getFieldErrors();

        int length = fieldErrors.size();

        for (int i = length - 1; i >= 0; i--)
        {
          FieldError error = (FieldError)fieldErrors.get(i);

          if (gbk(error.getDefaultMessage())) {
            if (i != 0)
            {
              errorMsg = errorMsg + error.getDefaultMessage() + "<br />&nbsp;&nbsp;&nbsp;";
            }
            else {
              errorMsg = errorMsg + error.getDefaultMessage();
            }
          }
        }
        return errorMsg;
      }
      return "";
    }

    private static boolean gbk(String str)
    {
         boolean flag = false;
        String charEncode = "GBK";  
        try {  
            if(str.equals(new String(str.getBytes(charEncode),charEncode))){  
                flag = true;
            }  
        } catch (UnsupportedEncodingException e) {  
            flag = false;
        }  
        return flag;
    }
}
